
import axios from 'axios'
// import { getStore } from '@/utils/store'
import store from '@/store'
import {serialize} from '@/utils/util'
import {errorCode} from '@/utils/setting'
import {Message} from 'element-ui'

import qs from 'qs'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// const baseURL = '/api/'
// create an axios instance
const service = axios.create({
  // baseURL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  },
  validateStatus: function (status) {
    return status >= 200 && status <= 500 // 默认的
  }
})

// NProgress Configuration
NProgress.configure({
  showSpinner: false
})

// HTTPrequest拦截
service.interceptors.request.use(
  config => {
    NProgress.start() // start progress bar
    // const token = getStore({name: 'TOKEN'})
    const token = store.getters.getToken
    token && (config.headers["App-Access-Token"] = token);

    // headers中配置serialize为true开启序列化
    if (config.method === 'post' && config.headers.serialize) {
      config.data = serialize(config.data)
      delete config.data.serialize
    }

    if (config.method === 'get') {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// HTTPresponse拦截
service.interceptors.response.use(
  res => {
    NProgress.done()
    const status = Number(res.status) || 200
    const message = res.data.msg || errorCode[status] || errorCode['default']
    if (status !== 200) {
      Message({message: message, type: 'error'})
      return Promise.reject(new Error(message))
    }
    return res
  },
  error => {
    NProgress.done()
    return Promise.reject(new Error(error))
  }
)

export default service
